//
//  ViewController.swift
//  66.照片选择器
//
//  Created by apple on 16/3/10.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class CZPhotoSelectorController: UICollectionViewController {
    
    private let layout = UICollectionViewFlowLayout()
    
    private let ReuseIdentifier = "ReuseIdentifier"
    
    /// 当前用户点击的cell的indexPath
    private var currentIndexPath: NSIndexPath?
    
    /// 图片最大张数
    private let maxCount = 6
    
    /// 选中的图片数组
    var photos: [UIImage] = [UIImage]()
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    init() {
        super.init(collectionViewLayout: layout)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        prepareCollectionView()
    }
    
    /**
     设置collectionView
     */
    private func prepareCollectionView() {
        let WH: CGFloat = 80
        let margin: CGFloat = 10
        layout.itemSize = CGSize(width: WH, height: WH)
        layout.minimumInteritemSpacing = margin
        layout.minimumLineSpacing = margin
        
        layout.sectionInset = UIEdgeInsets(top: 0, left: margin, bottom: 0, right: margin)
        
        collectionView?.backgroundColor = UIColor.whiteColor()
        collectionView?.dataSource = self
        collectionView?.registerClass(CZPhotoSelectorCell.self, forCellWithReuseIdentifier: ReuseIdentifier)
    }
}

extension CZPhotoSelectorController {
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // 1.当图片小于最大张数时,显示图片和加号按钮 返回 图片数量 + 1
        // 2.当图片等于最大张数时,显示图片,不需要加号 返回 图片数量
        return photos.count == maxCount ? photos.count : photos.count + 1   // 1是用来显示加号按钮的
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ReuseIdentifier, forIndexPath: indexPath) as! CZPhotoSelectorCell
        
        cell.backgroundColor = UIColor.brownColor()
        
        // 5.设置代理
        cell.delegate = self
        
        // 3.设置闭包
        cell.addButtonCallBack = { (cell: CZPhotoSelectorCell) -> () in
            print("在闭包里面监听到了加号按钮点击")
        }
        
        cell.deleteButtonCallBack = { (cell: CZPhotoSelectorCell) -> () in
            print("在闭包里面监听到了删除按钮点击")
        }
        
        // photos数组里面有图片才需要显示
        if indexPath.item < photos.count {
            cell.image = photos[indexPath.item]
        } else {
            // 需要显示加号按钮
            print("需要显示加号按钮")
            cell.setupAddButton()
        }
        
        return cell
    }
}

// 6.实现协议
extension CZPhotoSelectorController: CZPhotoSelectorCellDelegate {

    /// 加号按钮点击了
    func photoSelectorCell(cell: CZPhotoSelectorCell, addButtonClick: UIButton) {
        let pickerVC = UIImagePickerController()
        
        // 设置代理
        pickerVC.delegate = self
        
        // 找到cell对应的indexPath
        currentIndexPath = collectionView?.indexPathForCell(cell)
        
        presentViewController(pickerVC, animated: true, completion: nil)
    }
    
    func photoSelectorCell(cell: CZPhotoSelectorCell, deleteButtonClick: UIButton) {
        // 先获取点击的是哪个位置的删除按钮
        let indexPath = collectionView?.indexPathForCell(cell)
        
        photos.removeAtIndex(indexPath!.item)
        
        collectionView?.reloadData()
    }
}

/*
    修改图片功能:
        1.记录下点击的cell indexPath
        2.当选择完图片在collectionView?.reloadData()判断刚才点击的是否是加号
        3.是加号按钮就添加图片
        4.不是加号按钮修改图片
*/

/// 扩展 CZPhotoSelectorController 实现 UIImagePickerControllerDelegate, UINavigationControllerDelegate
extension CZPhotoSelectorController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    /// 系统照片选择器选择了一张照片, 当我们实现了这个方法需要我们自己来关闭控制器
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
//        print("我选中了一张图片: \(image)")
        
        // 缩小图片
        let newImage = image.scaleImage()
        print("我选中了一张图片: \(newImage)")
        
        // 判断点击的是加号还是图片,当indexPath == 图片的数量时,就是加号按钮
        if currentIndexPath?.item == photos.count {
            // 将图片添加到数组
            photos.append(newImage)
        } else {
            // 点击的是图片,修改图片
            photos[currentIndexPath!.item] = newImage
        }
        
        // 通知collectionView显示
        collectionView?.reloadData()
        
        // 关闭控制器
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}
